package com.example.searchservice.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchConfiguration;


import java.time.Duration;

@Configuration
public class ElasticsearchConfig extends ElasticsearchConfiguration {

    @Value("${spring.elasticsearch.uris}")
    private String[] elasticsearchUris;

    @Value("${spring.elasticsearch.username}")
    private String username;

    @Value("${spring.elasticsearch.password}")
    private String password;

    @Value("${spring.elasticsearch.connection-timeout}")
    private Duration connectionTimeout;

    @Value("${spring.elasticsearch.socket-timeout}")
    private Duration socketTimeout;

    @Value("${elasticsearch.client.max-connections:20}")
    private int maxConnections;

    @Value("${elasticsearch.client.max-connections-per-route:10}")
    private int maxConnectionsPerRoute;

    @Override
    public ClientConfiguration clientConfiguration() {
        ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(elasticsearchUris)
//                .usingSsl() // Spring Boot 3.1 默认启用 SSL
                .withBasicAuth(username, password)
                .withConnectTimeout(connectionTimeout)
                .withSocketTimeout(socketTimeout)
                .build();

        return clientConfiguration;
    }

    // 可选：如果你还需要直接使用 ElasticsearchClient
//    @Bean
//    public ElasticsearchClient elasticsearchClient(RestClient clientConfiguration) {
//        return super.elasticsearchClient(clientConfiguration);
//    }
//
//    // 可选：如果你需要低级别的 RestClient
//    @Bean
//    public RestClient restClient(ClientConfiguration clientConfiguration) {
//        return super.elasticsearchRestClient(clientConfiguration);
//    }
}